//
//  LoginViewController.swift
//  BaseSwift
//
//  Created by ghwang on 2019/7/22.
//  Copyright © 2019 ghwang. All rights reserved.
//

import UIKit

class LoginViewController: UIViewController,UITextFieldDelegate {

    let commitBtn = UIButton()

    let tf = UITextField()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationView.setTitle("")
        self.view.backgroundColor = UIColor.white
        self.navigationView.removeAllLeftButton()
        self.navigationView.addLeftButton(with: UIImage(named: "关闭")) { (view) in
            
            if (self.navigationController?.viewControllers.count)! > 1{
                
                POP(vc: self)

            }else{
                
                APP.initMainVC()
            }
        }
        
        
        let label = UILabel()
        let attrString = NSMutableAttributedString(string: "欢迎找到好去处")
        label.frame = CGRect(x: 32, y: HT_StatusBarAndNavigationBarHeight+24, width: 300, height: 30)
        label.numberOfLines = 0
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 30),.foregroundColor: UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        label.attributedText = attrString
        view.addSubview(label)
        
        let inputBg = UIView()
        self.view.addSubview(inputBg)
        let _ = inputBg.sd_layout()?.leftSpaceToView(view,32)!.rightSpaceToView(view,32)!.topSpaceToView(label,64)!.heightIs(45)
        
        let cBtn = UIButton()
        cBtn.setTitle("+86", for: .normal)
        inputBg.addSubview(cBtn)
        cBtn.setTitleColor(UIColor.textTitleColor, for: .normal)
        cBtn.titleLabel?.font = UIFont.commonFontSmaller
        let _ = cBtn.sd_layout()?.leftSpaceToView(inputBg,0)!.heightIs(30)!.centerYEqualToView(inputBg)!.widthIs(35)
        
        tf.font = UIFont.systemFont(ofSize: 20)
        tf.textColor = UIColor.textTitleColorBlack
        tf.placeholder = "请输入手机号"
        tf.clearButtonMode = .whileEditing
        tf.delegate = self
        tf.keyboardType = .phonePad
        inputBg.addSubview(tf)
        tf.addTarget(self, action: #selector(textFieldEditingChanged), for: .editingChanged)

        let _ = tf.sd_layout()?.leftSpaceToView(cBtn,16)!.rightSpaceToView(inputBg,16)!.heightIs(35)!.centerYEqualToView(inputBg)
        
        
        
        let bline = UIView()
        bline.backgroundColor = UIColor.lineColor
        inputBg.addSubview(bline)
        let _ = bline.sd_layout()?.widthRatioToView(inputBg,1)!.heightIs(1)!.bottomSpaceToView(inputBg,0)
        
        
        
        commitBtn.addTarget(self, action: #selector(getCodeClick), for: .touchUpInside)
        view.addSubview(commitBtn)
        commitBtn.isEnabled = false
        commitBtn.sd_cornerRadius = LARAGE_BTN_RADIUS
        let _ = commitBtn.sd_layout()?.leftSpaceToView(view,24)?.rightSpaceToView(view,24)?.heightIs(LARAGE_BTN_HEIGHT)?.centerXEqualToView(view)?.topSpaceToView(inputBg,35)
        
        commitBtn.backgroundColor = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.2)
        
        let tlab = UILabel()
        tlab.text = "获取验证码"
        tlab.tag = 9090
        tlab.font = UIFont.commonFont
        tlab.textColor = UIColor.white
        tlab.textAlignment = .center
        commitBtn.addSubview(tlab)
        let _ = tlab.sd_layout()?.spaceToSuperView(UIEdgeInsets.zero)
        
        if UIApplication.shared.canOpenURL(URL(string: "wechat://")!) {
            
            let wxBtn = UIButton()
            wxBtn.addTarget(self, action: #selector(wxBtnClick), for: .touchUpInside)
            wxBtn.setImage(UIImage(named: "wx_login"), for: .normal)
            view.addSubview(wxBtn)
            let _ = wxBtn.sd_layout()?.widthIs(24)!.heightIs(24)!.centerXEqualToView(view)!.bottomSpaceToView(view,HT_TabbarSafeBottomMargin+16)
            
            let lab0 = UILabel()
            lab0.text = "更多登录方式"
            lab0.textAlignment = .center
            lab0.textColor = UIColor.textTitleColor
            lab0.font = UIFont.commonFontSmaller
            view.addSubview(lab0)
            let _ = lab0.sd_layout()?.widthIs(200)!.bottomSpaceToView(wxBtn,10)!.centerXEqualToView(view)!.heightIs(20)
        }
    }

    @objc func textFieldEditingChanged(textfield:UITextField){
        
        if tf.text?.phoneValidate == true {
            
            commitBtn.gradientBtnMainColor()
            commitBtn.isEnabled = true
            let lab = commitBtn.viewWithTag(9090)
            commitBtn.bringSubviewToFront(lab!)

        }else{
            
            commitBtn.backgroundColor = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.2)
            commitBtn.isEnabled = false
            for item in commitBtn.layer.sublayers!{
                
                if item is CAGradientLayer{
                    
                    item.removeFromSuperlayer()
                }
            }

        }
    }
    @objc func wxBtnClick(){
        
    
        let req = SendAuthReq()
        req.scope = "snsapi_userinfo"
        WXApi.sendAuthReq(req, viewController: self, delegate: nil) { (result) in
            
            
        }
        APP.wxAuthSuccess = {(code) in
        
            print("code:\(code)")
            
            API.infoForCode(params: ["code":code]) { (result) in
                
                SPUtil.init().loginStatus = 1
                let login = result as! LoginResult
                SPUtil.init().token = login.appToken
                ALNetHTTPCommonConfig.appToken = login.appToken!
                SPUtil.init().leaguerId = login.userId ?? ""
                SPUtil.init().mobile = login.mobile ?? ""
                SPUtil.init().headImg = login.headImg ?? ""
                                if login.sex == "1"{
                                    
                                    SPUtil.init().sex = "男"

                                }else if login.sex == "2"{
                                    
                                    SPUtil.init().sex = "女"
                                }else{
                                    
                                    SPUtil.init().sex = ""

                }
                SPUtil.init().birthDay = login.birthDay ?? ""
                SPUtil.init().nickName = login.nickName ?? ""
                
                
                //如果没有手机号
                if login.mobile?.isEmpty == true{
                    
                    PUSH(from: self, to: BindPhoneVC())
                    
                }else{
                    
                    if APP.backToVC != nil {
                        

                        
                        self.navigationController?.popToViewController(APP.backToVC!, animated: true)
                        return

                    }
                    //跳转新页面
                    APP.initMainVC()
                }

                
                
            }
            
        }
        
    }
    @objc func getCodeClick(){
        
        if tf.text?.phoneValidate == false{
            
            ToastUtil.show(msg: "请输入有效的手机号")
            return
        }
        
        API.sendCode(params: ["mobile":tf.text!,
                                  ]) { (any) in
                                    
                                    ToastUtil.show(msg: "发送成功，请查收短信")
                                    let dvc = InputCodeVC()
                                    dvc.phone = self.tf.text!
                                    PUSH(from: self, to: dvc)

        }
        
    }
    
    func textFieldDidChangeSelection(_ textField: UITextField) {
        
        
    }
    
}
